package com.itboye.ihomebank.home;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.itboye.ihomebank.MainActivity;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.adapter.HeTongAdapter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.HeTongBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.db.HeTongDBManager;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.qianyue.OrderFragment;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.DoubleDatePickerDialog;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;

public class TianXieHeTongActivityZuKe extends BaseOtherActivity implements
		Observer {

	UserPresenter userPresenter;
	TextView add_shap_title_tv;
	LinearLayout li_container;
	Button tijiao;
	private int selectStartYear;
	private int selectEndYear;

	private int selectStartMonth;
	private int selectEndMonth;
	ArrayList<TextView> devices = new ArrayList<>();
	ArrayList<View> views = new ArrayList<>();
	int index;
	Calendar dateAndTime = Calendar.getInstance(Locale.CHINA);
	private String uid;
	private String contractNo;

	ArrayList<EditText> editTexts = new ArrayList<>();
	private String selectDevice;
	private String selectFeiYong;
	private String unselectFeiYong;
	protected int qishu;
	protected String yajin;
	Calendar current = Calendar.getInstance();
	private String jsonStr;

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.close_icon:
			finish();
			break;
		case R.id.tijiao:
			buildJson();// 生成json数据
			break;
		default:
			break;
		}
	}

	public void buildJson() {
		Gson gson = new Gson();
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < views.size(); i++) {
			EditText editText = (EditText) views.get(i).findViewById(R.id.edit);
			if (views.get(i).getTag().equals("sign_renter")) {// 房租信息
				map.put(editText.getTag() + "", imgId);
			}
			// else if (views.get(i).getTag().equals("start_date")
			// || views.get(i).getTag().equals("end_date")) {
			// TextView textView = (TextView) views.get(i).findViewById(
			// R.id.txt_device);
			// map.put(editText.getTag() + "", textView.getText().toString());
			// }
			else {
				map.put(editTexts.get(i).getTag() + "", editTexts.get(i)
						.getText().toString());
			}
		}
		for (int i = 0; i < editTexts.size(); i++) {

		}
		jsonStr = gson.toJson(map);
		HeTongDBManager dbManager = new HeTongDBManager(this);
		long re = dbManager.addNote(uid, contractNo, "renter", jsonStr);
		if (re > 0) {
			ByAlert.alert("添加成功" + contractNo);
		} else {
			ByAlert.alert("添加失败");
		}
		userPresenter.tiJiaoHeTong(uid, contractNo, jsonStr);
		System.out.println("》》生成的json字符串" + jsonStr);
	}

	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		return R.layout.activity_hetong;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onInit() {
		// TODO Auto-generated method stub
		add_shap_title_tv.setText("填写合同");
		uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
		contractNo = getIntent().getStringExtra("contractNo");
		userPresenter = new UserPresenter(this);
		userPresenter.heTongParams("1", contractNo);
	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == UserPresenter.heTongParams_success) {
				List<HeTongBean> datas = (List<HeTongBean>) entity.getData();
				// HeTongAdapter adapter = new HeTongAdapter(this, datas,
				// R.layout.item_hetong);
				for (int i = 0; i < datas.size(); i++) {
					HeTongBean bean = datas.get(i);
					Integer inputType = bean.getValueType();// 5、整型 1、字符串 4、日期
															// 0、点击进去 2、签字

					final View view = LayoutInflater.from(this).inflate(
							R.layout.item_hetong, null);
					TextView txt_device = (TextView) view
							.findViewById(R.id.txt_device);
					devices.add(txt_device);
					TextView text = (TextView) view.findViewById(R.id.txt);
					EditText editText = (EditText) view.findViewById(R.id.edit);
					switch (inputType) {// 1: 文本、2: 图片、3: 当前时间 4：当前日期 5：数字 ,默认0
					case 1:
						editText.setInputType(InputType.TYPE_CLASS_TEXT);
						break;
					case 2:

						break;
					case 3:

						break;
					case 4:

						break;
					case 5:
						editText.setInputType(InputType.TYPE_CLASS_NUMBER);
						break;

					default:
						break;
					}
					editText.setTag(bean.getKey());
					editText.setHint(bean.getDesc());
					if (!bean.get_default().equals("")) {
						editText.setEnabled(false);
						editText.setText(bean.get_default());
					}
					if (bean.getKey().equals("sign_renter")) {
						editText.setEnabled(false);
					}
					if (bean.getKey().equals("sign_renter_date")) {
						editText.setText(current.get(Calendar.YEAR)
								+ "-"
								+ ((current.get(Calendar.MONTH) + 1) + "-" + current
										.get(Calendar.DATE)));
						editText.setEnabled(false);
					}
					editTexts.add(editText);// 将所有的编辑框放进集合

					text.setText(bean.getAlias());
					li_container
							.addView(view, li_container.getChildCount() - 1);
					view.setTag(datas.get(i).getKey() + "");
					views.add(view);
					view.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub

							if ((v.getTag() + "").equals("sign_renter")) {// 乙方签字
								Intent intent = new Intent(
										TianXieHeTongActivityZuKe.this,
										ActivityHuaBan.class);
								startActivityForResult(intent, 107);//
							}
						}
					});
				}
			} else if (entity.getEventType() == UserPresenter.heTongParams_fail) {
				ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == UserPresenter.heTongTiJiao_success) {
				Intent intent = new Intent();
				intent.putExtra("shenfen", "renter");
				intent.putExtra("contractNo", contractNo);
				sendBroadcast(intent);
				OrderFragment.getInstance().refresh();
				finish();
				ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == UserPresenter.heTongTiJiao_fail) {
				ByAlert.alert(entity.getData());
			}
		}
	}

	// 当点击DatePickerDialog控件的设置按钮时，调用该方法
	DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// 修改日历控件的年，月，日
			// 这里的year,monthOfYear,dayOfMonth的值与DatePickerDialog控件设置的最新值一致
			dateAndTime.set(Calendar.YEAR, year);
			dateAndTime.set(Calendar.MONTH, monthOfYear);
			dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			// 将页面TextView的显示更新为最新时间
			for (View v : views) {
				TextView text = (TextView) v.findViewById(R.id.txt_device);
				if (v.getTag().toString().equals("start_date")) {
					updateLabel(text);
				}
				if (v.getTag().toString().equals("end_date")) {
					v.findViewById(R.id.txt_device).setVisibility(View.VISIBLE);
					((TextView) v.findViewById(R.id.txt_device))
							.setText(selectFeiYong);
					updateLabel(text);
				}
			}

		}
	};
	private String zujinxinxi;
	private String imgId;

	// 更新页面TextView的方法
	private void updateLabel(TextView dateAndTimeLabel) {
		dateAndTimeLabel.setVisibility(View.VISIBLE);
		dateAndTimeLabel.setText(TimesUtils.timeDate(Long.parseLong(dateAndTime
				.getTime().toString())));

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 107 && resultCode == 108) {// 上传签字图片
			imgId = data.getStringExtra("imgId");
			for (View v : views) {
				if (v.getTag().toString().equals("sign_renter")) {
					v.findViewById(R.id.edit).setVisibility(View.VISIBLE);
					((EditText) v.findViewById(R.id.edit)).setText("已签名");
				}
			}
		}

	}

}
